<template>
  <div class="container">
    <div class="app-container">
      <el-tree :expand-on-click-node="false" default-expand-all :data="depts" :props="defaultProps" node-key>
        <template v-slot="{ data }">
          <el-row style="width: 100%;height: 40px;" type="flex" justify="space-between" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="tools">{{ data.managerName }}</span>
              <el-dropdown @command="handleCommand($event, data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <AddDept ref="addDept" @updateDepartment="getDepartment" :currentNodeId="currentNodeId"
      :showDialog.sync="showDialog" />
  </div>
</template>
<script>
import { getDepartment, delDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
import AddDept from './components/add-dept.vue'
export default {
  name: 'Department',
  components: {
    AddDept
  },
  data() {
    return {
      currentNodeId: null,
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children',
      },
      showDialog: false,
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      const res = await getDepartment()
      this.depts = transListToTreeData(res, 0)
    },
    handleCommand(command, id) {
      if (command === 'add') {
        this.showDialog = true
        this.currentNodeId = id
      } else if (command === 'edit') {
        this.showDialog = true
        this.currentNodeId = id
        this.$nextTick(() => {//// 使用$nextTick确保DOM更新完毕后执行回调
          this.$refs.addDept.getDepartmentDetail()
          // 调用addDept组件的getDepartmentDetail方法，用于获取部门详情
        })
      } else if (command === 'del') {
        //删除部门
        this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          //删除部门
          await delDepartment(id)
          this.$message.success('删除成功!')
          this.getDepartment()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    }
  }

}
</script>
<style>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}

.container {
  padding: 20px;
  min-height: calc(100vh - 80px);
}

.tools {
  width: 50px;
  display: inline-block;
  margin: 27px;
}
</style>